package com.JFapp.listeners;

import com.JFapp.constants.SystemConstants;
import com.JFapp.controller.WebsocketController;
import com.JFapp.domain.entity.Repair;

import com.JFapp.service.PerformanceService;
import com.JFapp.service.RepairService;
import com.JFapp.service.UserService;
import com.JFapp.utils.RedisCache;


import com.JFapp.utils.WebsocketUtil;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

@Component
public class repairListener {


    @Autowired
    private RedisCache redisCache;
    @Autowired
    private PerformanceService performanceService;
    @Autowired
    private WebsocketUtil websocketUtil;
    @Autowired
    private UserService userService;
    private static final ObjectMapper objectMapper = new ObjectMapper();

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "addRepair"),
            exchange = @Exchange(name = "repairExchange"),
            key = {"repair.add"}
    ))
    public void listenRepair(Repair repair)  {
        WebsocketUtil.sendMessageForAll("你有新的维修单："+repair.getRepairId());
    }


    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "finishRepair"),
            exchange = @Exchange(name = "repairExchange"),
            key = {"repair.finish"}
    ))
    public void finishRepair(Repair repair){
        redisCache.updateZSet(SystemConstants.PERFORMANCE_RANK,repair.getReceiver(),repair.getPerformancePrice().doubleValue());
        performanceService.addRecords(repair);

        WebsocketUtil.sendMessage(userService.selectID(repair.getReceiver()),"第"+repair.getRepairId()+"号维修单完成");

    }


}
